import React from 'react';
import { Descriptions, message, Button, Image, Divider, Row, Col, Modal, Upload, Input, Comment, List, Tabs, Avatar, Tag } from 'antd';
import axios from 'axios';
import { Url } from '../url';
import { FireOutlined, DeleteOutlined, HeartTwoTone, HeartOutlined, MinusCircleOutlined, ExclamationCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { Typography } from 'antd';
import { Statistic, InputNumber, Popover, Result } from 'antd';
import { AskService } from './ask-mangement';

const { Countdown } = Statistic;
const { confirm } = Modal;

const { Title, Paragraph } = Typography;

const { TextArea } = Input;
const { TabPane } = Tabs;

export class AskDetail extends React.Component {
    state = {
        ask: { commentList: [], bidList: [] },
        showModal: false,
        showbidPrice: false,
        bid: 0,  ///bid price in model
        bidFileUrl: undefined,
        bidFileId: undefined
    }

    currentUser = {}
    componentDidMount = () => {
        if (localStorage.getItem("user") == null) {
            message.info("Please login first")
            setTimeout(() => {
                window.location.href = "/#/login";
            }, 50);
        } else {

            this.currentUser = JSON.parse(localStorage.getItem("user"));

            // console.log(this.props.match.params.id)
            this.getAsk();
        }
    }

    //封装Ask请求
    getAsk = () => {
        axios.get(Url.getAsk + this.props.match.params.id)
            .then((response) => {
                console.log(response)
                this.setState({
                    ask: response.data,
                    bid: response.data.cost
                })
            })
            .catch((error) => {
                message.error("Network Error");
                console.log(error);
            });
    }

    //点击显示输入bid价格的框
    showBidModal = () => {
        this.setState({
            showbidPrice: true,
        });
    }

    onBidChange = (bid) => {
        this.setState({
            //弹出框中输入的评论，bid.target.value返回值是个对象
            bid: bid,
        });
    }

    bidOk = () => {
        //当返回bid对象是null，即没有输入任何bid price时，弹出error message
        if (this.state.bid == null) {
            message.error("please input your bid price")
        } else if (this.state.bidFileId == null) {

            message.error("please upload your docunment")

        } else {
            //点击ok时，showbidPrice: false,代表可以关闭此modal框
            this.setState({
                showbidPrice: false,
            })
            //将userId，bidPrice，askId封装在对象values里面，传去后台
            const values = {
                userId: this.currentUser.userId,
                bidPrice: this.state.bid,
                askId: this.state.ask.askId,
                file: this.state.bidFileId
            }
            // post to the backend  
            axios.post(Url.bid, values).then((response) => {
                message.success("bid succeed")
                //bid成功后从后台拿数据，刷新页面
                this.getAsk();

                this.setState({
                    bidFileId: undefined,
                    bidFileUrl: undefined
                })

            }).catch((error) => {
                message.error("bid failed")
            })
        }
    }

    //点击cancel按钮时，将modal框关闭
    bidCancel = () => {
        this.setState({
            showbidPrice: false,
        })
    };

    //点击显示弹出评论的框
    showCommentModal = () => {
        this.setState({
            showModal: true,
        })
    }

    handleOk = () => {
        if (this.state.comment == null) {
            message.error("please input your comment")
        } else {
            this.setState({
                showModal: false,
            })
            const values = {
                askId: this.state.ask.askId,
                userId: this.currentUser.userId,
                detail: this.state.comment,
            }
            //post to the backend  
            axios.post(Url.comment, values).then((response) => {
                message.success("comment succeed")
                this.getAsk();

            }).catch((error) => {
                message.success("comment failed")
            })
        }
    };

    handleCancel = () => {
        this.setState({
            showModal: false,
        })
    };

    onCommentChange = (comment) => {
        this.setState({
            comment: comment.target.value,
        })
    }

    //删除评论
    delete = (id) => {
        axios.get(Url.deleteComment + id).then(() => {
            message.success("delete succeed")
            this.getAsk();
        }).catch((error) => {
            message.error("delete failed")
        })
    }

    //赢的中标
    win = (id) => {
        axios.post(Url.chooseBid + this.state.ask.askId + "/choose/" + id).then(() => {
            message.success("select succeed")
            this.getAsk();
        }).catch((error) => {
            message.error("select failed")
        })
    }

    formatDollar = (dollar) => {
        const dollarArray = String(dollar).split(".");
        const dollarInteger = dollarArray[0];
        let dollarDecimal = dollarArray[1];
        if (dollarDecimal == undefined) {
            dollarDecimal = "00"
        }
        return <span><span style={{ fontSize: "25px" }}>{"$"}</span><span style={{ fontSize: "40px" }}>{dollarInteger + "."}</span><span style={{ fontSize: "30px" }}>{dollarDecimal}</span></span>;
    }

    uploadFileProps = {
        name: 'file',
        action: Url.uploadFile,
        onChange: (info) => {
            if (info.file.status !== 'uploading') {
                this.setState({
                    bidFileUrl: Url.downloadFile + "/" + info.file.response,
                    bidFileId: info.file.response
                });
            }
            if (info.file.status === 'done') {
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        showUploadList: {
            showDownloadIcon: false,
            showRemoveIcon: false,
        },
    };

    render = () => {

        const colorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae'];


        let timePanel = <Row>
            <Col span={12}>
                <Statistic title="Deadline" style={{ marginTop: "16px" }} value={(new Date(this.state.ask.endTime)).toLocaleDateString()} />
            </Col>
            <Col span={12}>
                <Countdown title="Remain" style={{ marginTop: "16px" }} value={new Date(this.state.ask.endTime).getTime()} />
            </Col>
        </Row>

        if ((new Date()).getTime() < this.state.ask.startTime) {
            timePanel = <Row>
                <Col span={12}>
                    <Statistic title="Open Bid Date" style={{ marginTop: "16px" }} value={(new Date(this.state.ask.startTime)).toLocaleDateString()} />
                </Col>
                <Col span={12}>
                    <Countdown title="Before Open" style={{ marginTop: "16px" }} value={new Date(this.state.ask.startTime).getTime()} />
                </Col>
            </Row>
        }

        if (this.state.ask.state === "finish") {
            timePanel = <Row>
                <Col span={12}>
                    <Statistic title="Win UserId" style={{ marginTop: "16px" }} value={this.state.ask.winBid.userId} />
                </Col>
                <Col span={12}>
                    <Countdown title="Remain" style={{ marginTop: "16px" }} value={0} />
                </Col>
            </Row>
        }


        const getStateTag = (ask) => {
            const state = AskService.getAskState(ask);
            if (state === "ready") {
                return <Tag color="purple" icon={<FireOutlined />}>Ready</Tag>
            } else if (state === "start") {
                return <Tag color="green" icon={<FireOutlined />}>In progress</Tag>
            } else if (state === "cancel") {
                return <Tag icon={<MinusCircleOutlined />} color="default">Canceled</Tag>
            } else if (state === "finish") {
                return <Tag icon={<MinusCircleOutlined />} color="default">Finished</Tag>
            } else {
                return <Tag icon={<MinusCircleOutlined />} color="default">Stopped</Tag>
            }
        }

        // let state = <></>;
        // if (this.state.ask != undefined && this.state.ask.state === "cancel") {
        //     state = <Tag icon={<MinusCircleOutlined />} color="default">
        //         Canceled
        //     </Tag>;

        // }

        const formatDollar = (dollar) => {
            const dollarArray = String(dollar).split(".");
            const dollarInteger = dollarArray[0];
            let dollarDecimal = dollarArray[1];
            if (dollarDecimal == undefined) {
                dollarDecimal = "00"
            }
            return <span><span style={{ fontSize: "11px" }}>{"$ "}</span><span>{dollarInteger + "."}</span><span style={{ fontSize: "12px" }}>{dollarDecimal}</span></span>;
        }

        let bidPanel = <></>

        if (this.currentUser.admin) {
            bidPanel = <List
                itemLayout="horizontal"
                dataSource={this.state.ask.bidList}
                renderItem={item => (
                    <li>
                        <Comment
                            actions={[<Button type="text" disabled={this.state.ask.state === "finish"} onClick={() => {

                                confirm({
                                    title: 'Confirm',
                                    icon: <ExclamationCircleOutlined />,
                                    content: 'Are you want to select this bid. You can\'t change after you select it.',
                                    okText: 'Select',
                                    cancelText: 'Cancel',
                                    onOk: () => {
                                        this.win(item.bidId);
                                    },
                                    onCancel: () => {

                                    }
                                });

                            }}>
                                {item.win ? <HeartTwoTone twoToneColor="#eb2f96" /> : <HeartOutlined />}
                                <span className="comment-action" style={{ marginLeft: "8px" }}>Select this bid</span>
                            </Button>]}
                            author={item.userId}
                            avatar={
                                <Avatar style={{ backgroundColor: colorList[Math.floor(Math.random() * 4)], verticalAlign: 'middle' }}>
                                    {item.userId.slice(0, 1).toUpperCase()}
                                </Avatar>
                            }
                            content={
                                <div>
                                    <span style={{ color: "darkred", fontWeight: "bold", marginRight: 16 }}>{formatDollar(item.bidPrice)}</span>
                                    <a href={Url.downloadFile + "/" + item.file}>Preview</a>
                                </div>
                            }
                            datetime={new Date(item.bidTime).toLocaleDateString() + " " + (new Date(item.bidTime)).toLocaleTimeString()}
                        />
                    </li>
                )}
            />
        } else {
            bidPanel = <Result
                status="403"
                title="403"
                subTitle="Sorry, only admin can view all the bids."
            />
        }

        let preview = <></>
        if (this.state.bidFileUrl) {
            preview = <a href={this.state.bidFileUrl}>Preview</a>
        }


        return (

            <div style={{ width: "100%", display: "flex", justifyContent: "center", backgroundColor: "#f0f0f0" }}>
                <div style={{ width: "70%", paddingTop: "32px", paddingRight: "32px", paddingLeft: "32px", backgroundColor: "white" }}>
                    <Row>
                        {/* 左右布局，左边占6格 */}
                        <Col span={16}>
                            <Image
                                width={"40vw"}
                                src={Url.viewImage + this.state.ask.cover}
                            />
                        </Col>
                        {/* 右边占18格 */}
                        <Col span={8}>
                            <div style={{ textAlign: 'left' }}>
                                <Row>
                                    <Col span={12}>
                                        <Title level={2} style={{ fontWeight: "bolder" }}>{this.state.ask.name}</Title>
                                    </Col>
                                    <Col span={12} style={{ marginTop: "11px" }}>
                                        {getStateTag(this.state.ask)}
                                    </Col>
                                </Row>
                                <Paragraph>{this.state.ask.description}</Paragraph>
                            </div>
                            <div>
                                <span style={{ fontSize: "20px", fontWeight: "bold", color: "#666", marginRight: "36px" }}>Budget: </span>
                                <span style={{ fontWeight: "bolder", color: "darkred" }}>{this.formatDollar(this.state.ask.cost)}</span>
                            </div>

                            {timePanel}
                            <Statistic title="Total Bid Users" value={this.state.ask.bidList ? this.state.ask.bidList.length : 0} style={{ marginTop: "16px" }} />

                            <Button disabled={(new Date()).getTime() < this.state.ask.startTime || (new Date()).getTime() > this.state.ask.endTime || this.state.ask.state === 'cancel' || this.state.ask.state === 'finish' || this.currentUser.admin} type="primary" danger style={{ marginTop: "16px" }} onClick={this.showBidModal}>Bid Now</Button>
                        </Col>
                    </Row>
                    <Divider orientation="left">Information</Divider>
                    <Descriptions bordered>
                        <Descriptions.Item label="Name">{this.state.ask.name}</Descriptions.Item>
                        <Descriptions.Item label="Description">{this.state.ask.description}</Descriptions.Item>
                        <Descriptions.Item label="Category">{this.state.ask.category}</Descriptions.Item>
                        <Descriptions.Item label="Phone">{this.state.ask.phone}</Descriptions.Item>
                        <Descriptions.Item label="Company">{this.state.ask.company}</Descriptions.Item>
                        <Descriptions.Item label="Budget">{this.state.ask.cost}</Descriptions.Item>
                        <Descriptions.Item label="StartTime">{(new Date(this.state.ask.startTime)).toLocaleDateString() + " " + (new Date(this.state.ask.startTime)).toLocaleTimeString()}</Descriptions.Item>
                        <Descriptions.Item label="EndTime">{(new Date(this.state.ask.endTime)).toLocaleDateString() + " " + (new Date(this.state.ask.endTime)).toLocaleTimeString()}</Descriptions.Item>
                    </Descriptions>
                    <Divider orientation="left">Detail</Divider>
                    <div dangerouslySetInnerHTML={{ __html: this.state.ask.detail }}></div>

                    <a href={Url.downloadFile + "/" + this.state.ask.file}>Download docunment</a>
                    <Modal title="please input your comment" visible={this.state.showModal} onOk={this.handleOk} onCancel={this.handleCancel}>
                        <TextArea rows={4} onChange={this.onCommentChange} />
                    </Modal>
                    <Modal
                        title={
                            <Popover content={<div>Note: The bid price could not be larger than the budget.</div>}>
                                Please input your expected bid price.
                            </Popover>
                        } visible={this.state.showbidPrice} onOk={this.bidOk} onCancel={this.bidCancel}>
                        {/* <TextArea rows={1} onChange={this.onBidChange} /> */}
                        <InputNumber
                            style={{ marginRight: 16 }}
                            min={0}
                            max={this.state.ask.cost}
                            defaultValue={this.state.ask.cost}
                            formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                            parser={value => value.replace(/\$\s?|(,*)/g, '')}
                            onChange={this.onBidChange}
                        />
                        <Upload {...this.uploadFileProps}>
                            <Button icon={<UploadOutlined />}>Click to Upload</Button>
                        </Upload>
                        {preview}

                    </Modal>
                    <Divider orientation="left">Interactive</Divider>
                    <Tabs defaultActiveKey="Comment">
                        <TabPane tab={"Comment" + " (" + `${this.state.ask.commentList.length}` + ")"} key="Comment">
                            <Button type="primary" size="small" style={{ marginBottom: "32px" }} onClick={this.showCommentModal}>Publish Comment</Button>
                            <List
                                className="comment-list"
                                // header={`${this.state.ask.commentList.length} comment`}
                                itemLayout="horizontal"
                                dataSource={this.state.ask.commentList}
                                renderItem={item => (
                                    <li>
                                        <Comment
                                            actions={
                                                this.currentUser.admin || this.currentUser.userId === item.userId ? [<span
                                                    onClick={() => { this.delete(item.id) }}>
                                                    <DeleteOutlined />
                                                    <span className="comment-action" style={{ marginLeft: "8px" }}>delete</span>
                                                </span>] : []}
                                            author={item.userId}
                                            avatar={
                                                <Avatar style={{ backgroundColor: colorList[Math.floor(Math.random() * 4)], verticalAlign: 'middle' }}>
                                                    {item.userId.slice(0, 1).toUpperCase()}
                                                </Avatar>
                                            }
                                            content={item.detail}
                                            datetime={new Date(item.publishTime).toLocaleDateString() + " " + (new Date(item.publishTime)).toLocaleTimeString()}
                                        />
                                    </li>
                                )}
                            />
                        </TabPane>
                        <TabPane tab={"Bid" + " (" + `${this.state.ask.bidList.length}` + ")"} key="2">
                            {bidPanel}
                        </TabPane>

                    </Tabs>



                </div>
            </div >
        )
    }
}